import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Spin, Input, message } from 'antd';
import moment from 'moment';
import { PrimaryC, SecondHeaderC, TableC } from '../../../comps';
import myStyle from './index.less';
import uuid from 'es6-uuid';

@connect(({ investmentCalendarM, userM: user }) => ({
  investmentCalendarM,
  user,
}))
@Form.create()
export default class MsgC extends PureComponent {
  state = {
    dataSource: [],
    currentContent: '', //当前编辑内容
    date: '', //当前日期
    loading: false, //加载效果
    currentTime: '', //当前时间戳
  };
  componentDidMount() {
    this.setState(
      {
        date: this.props.date,
        currentTime: this.props.currentTime,
      },
      () => {
        this.queryMsgList(); //查询消息列表
      },
    );
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (
      this.state.currentTime != nextProps.currentTime ||
      this.state.date != nextProps.date ||
      JSON.stringify(nextProps.portfolioCodeList) !== JSON.stringify(this.state.portfolioCodeList)
    ) {
      this.setState(
        {
          date: nextProps.date,
          currentTime: nextProps.currentTime,
        },
        () => {
          this.queryMsgList(); //查询消息列表
        },
      );
    }
  }

  //修改编辑状态 决定展示编辑还是保存按钮
  clickEdit = (type, record) => {
    const { dataSource } = this.state;
    dataSource.map((item) => {
      if (item.id == record.id) {
        item.isEdit = type == 'edit' ? true : false;
      }
    });
    this.setState({
      dataSource: [...dataSource],
    });
  };

  //消息内容Input框更新
  changeContent = (e, record) => {
    const { dataSource } = this.state;
    dataSource.map((item) => {
      if (item.id == record.id) {
        item.message = e.target.value;
      }
    });
    this.setState({
      dataSource: [...dataSource],
      currentContent: e.target.value,
    });
  };

  //保存消息
  saveContent = (record) => {
    const { dataSource, date, currentContent } = this.state;
    const {
      currentUser: { userId },
    } = this.props.user;
    if (!currentContent) {
      message.warning('消息内容必填!');
      return;
    }
    //调用后台保存接口
    this.props.dispatch({
      type: 'investmentCalendarM/addOrEditMsg',
      payload: {
        message: currentContent,
        id: record.id.length == 16 ? undefined : record.id, //当前列id 新增不传 编辑传id
        dataDt: moment(date).format('YYYYMMDD'),
        userId,
      },
      callback: (type, data) => {
        if (type == 'success') {
          //成功之后
          this.clickEdit('save', record);
          this.queryMsgList('update');
        }
      },
    });
  };

  //查询消息列表
  queryMsgList = (queryType) => {
    const { date } = this.state;
    const {
      currentUser: { userId },
    } = this.props.user;
    this.setState({
      loading: true,
    });
    this.props.dispatch({
      type: 'investmentCalendarM/queryMsgList',
      payload: {
        dataDt: moment(date).format('YYYYMMDD'),
        userId: userId || localStorage.getItem('antd-pro-userId'),
      },
      callback: (type, data) => {
        if (type == 'success') {
          if (queryType == 'update') {
            this.props.onChange(data);
          }
          data.map((item) => {
            item.isEdit = false;
          });

          this.setState({
            dataSource: [...data],
          });
        } else {
          this.setState({
            dataSource: [],
          });
        }
        this.setState({
          loading: false,
        });
      },
    });
  };

  //删除消息
  delMsg = (id) => {
    this.props.dispatch({
      type: 'investmentCalendarM/delMsg',
      payload: {
        id,
      },
      callback: (type) => {
        if (type == 'success') {
          //成功之后 刷新列表
          this.queryMsgList('update');
        }
      },
    });
  };

  //新增消息 前端展示
  addMsg = () => {
    const { dataSource } = this.state;
    dataSource.unshift({
      id: uuid(16),
      isEdit: true,
    });
    this.setState({
      dataSource: [...dataSource],
    });
  };

  render() {
    const { dataSource, loading } = this.state;
    const columns = [
      {
        key: 'isEdit',
        title: '',
        className: myStyle.hide,
      },
      {
        key: 'message',
        title: '消息内容',
        onCell: () => {
          return {
            style: {
              maxWidth: 150,
              overflow: 'hidden',
              whiteSpace: 'nowrap',
              textOverflow: 'ellipsis',
              cursor: 'pointer',
            },
          };
        },
        render: (text, row) => {
          if (!row.isEdit) {
            return <span title={text}>{text}</span>;
          } else {
            return (
              <Input
                style={{ width: '100%' }}
                value={text}
                onChange={(e) => {
                  this.changeContent(e, row);
                }}
              />
            );
          }
        },
      },
      {
        key: 'operate',
        type: 'operate',
        title: '操作',
        className: myStyle.operate,
        operates: [
          {
            title: '编辑',
            onClick: (record, index) => {
              this.clickEdit('edit', record);
            },
            //按钮显示隐藏
            rules: {
              hide: { relation: 'and', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
            },
          },

          {
            title: '删除',
            onClick: (record, index) => {
              this.delMsg(record.id);
            },
            rules: {
              hide: { relation: 'and', items: [{ key: 'isEdit', value: [true], relation: ['='] }] },
            },
          },
          {
            title: '保存',
            onClick: (record, index) => {
              this.saveContent(record);
            },
            rules: {
              hide: { relation: 'and', items: [{ key: 'isEdit', value: [false], relation: ['='] }] },
            },
          },
          {
            title: '取消',
            onClick: (record, index) => {
              this.clickEdit('save', record);
              //重新请求消息列表
              this.queryMsgList();
            },
            rules: {
              hide: { relation: 'and', items: [{ key: 'isEdit', value: [false], relation: ['='] }] },
            },
          },
        ],
      },
    ];
    return (
      <div>
        <div style={{ position: 'relative' }}>
          <SecondHeaderC title={'消息列表'} />
          <div style={{ position: 'absolute', right: 0, top: '-10px' }}>
            <PrimaryC title={'新增'} onClick={this.addMsg} />
          </div>
        </div>
        <div style={{ height: '125px' }}>
          <Spin spinning={loading} tip='加载中...'>
            <TableC columns={columns} dataSource={dataSource} hidePage={true} scroll={dataSource && dataSource.length > 2 ? { x: '100%', y: '99px' } : {}} rowKey='id' />
          </Spin>
        </div>
      </div>
    );
  }
}
